import requests
import datetime


API_KEY = "ed55f06df550c7566352627065d6984f"

def get_weather( city, date=None, country_code=None):
    """
    调用OpenWeatherMap API获取某地某时间的天气
    
    参数:
        api_key (str): OpenWeatherMap API密钥
        city (str): 城市名称
        date (str, optional): 日期，格式YYYY-MM-DD，默认为今天
        country_code (str, optional): 国家代码，如'CN'，默认为'CN'
    
    返回:
        dict: 包含天气信息的字典，或错误信息
    """
    base_url = "http://api.openweathermap.org/data/2.5/forecast"
    
    # 构建查询参数
    q = city
    if country_code:
        q += f",{country_code}"
    
    params = {
        'q': q,
        'appid': API_KEY,
        'units': 'metric'  # 摄氏温度
    }
    
    try:
        # 发送请求
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()
        
        # 处理日期
        if not date:
            # 如果没有提供日期，获取当前天气
            forecast = data['list'][0]
        else:
            # 解析日期
            target_date = datetime.datetime.strptime(date, '%Y-%m-%d')
            # 在预报中查找最接近目标日期的时间点
            closest_forecast = None
            min_diff = float('inf')
            
            for item in data['list']:
                # API返回的时间格式为UTC时间戳
                forecast_time = datetime.datetime.fromtimestamp(item['dt'])
                # 计算与目标日期的时间差
                diff = abs((forecast_time.date() - target_date.date()).days)
                
                if diff < min_diff:
                    min_diff = diff
                    closest_forecast = item
                
                # 如果找到完全匹配的日期，提前结束循环
                if diff == 0:
                    break
            
            if not closest_forecast:
                return {"error": "无法获取指定日期的天气数据"}
            
            forecast = closest_forecast
        
        # 提取关键天气信息
        weather_info = {
            'date': datetime.datetime.fromtimestamp(forecast['dt']).strftime('%Y-%m-%d %H:%M:%S'),
            'description': forecast['weather'][0]['description'],
            'temperature': forecast['main']['temp'],
            'feels_like': forecast['main']['feels_like'],
            'humidity': forecast['main']['humidity'],
            'wind_speed': forecast['wind']['speed'],
            'city': data['city']['name'],
            'country': data['city']['country']
        }
        
        return weather_info
    
    except requests.exceptions.RequestException as e:
        return {"error": f"API请求错误: {str(e)}"}
    except ValueError as e:
        return {"error": f"日期格式错误，请使用YYYY-MM-DD格式: {str(e)}"}
    except Exception as e:
        return {"error": f"发生未知错误: {str(e)}"}

# 测试函数
if __name__ == "__main__":
    # 替换为你的实际API密钥
    API_KEY = "ed55f06df550c7566352627065d6984f"
    
    # 获取今天的天气
    today_weather = get_weather( "Beijing", country_code="CN")
    print("今天的天气:")
    for key, value in today_weather.items():
        print(f"{key}: {value}")
    
    # 获取指定日期的天气
    date_weather = get_weather( "Shanghai", "2025-07-10", "CN")
    print("\n2025年7月10日的天气:")
    for key, value in date_weather.items():
        print(f"{key}: {value}")    